import { useState, useRef } from "react";
import { Space, Input, Button, Image, message } from "antd";
import { addBannerInterface } from "@/api/banner";
import { useNavigate } from "react-router-dom";
export default function Add() {
  const [messageApi, contextHolder] = message.useMessage();
  const [link, setLink] = useState("");
  const [alt, setAlt] = useState("");
  const [img, setImg] = useState("");
  const fileRef = useRef();
  const navigate = useNavigate();

  const onChange = () => {
    const fileInfo = fileRef.current.input.files[0];
    // 限制文件类型
    const typeRight = ["image/jpeg", "image/jpg", "image/png"].includes(
      fileInfo.type
    );
    // 限制图片大小
    const sizeRight = fileInfo.size / 1024 / 1024 < 2;
    if (!typeRight) {
      messageApi.error("文件类型不对!");
      return false;
    }
    if (!sizeRight) {
      messageApi.error("图片大于2M!");
      return false;
    }

    // 图片地址转换base64
    const reader = new FileReader();
    reader.readAsDataURL(fileInfo);
    reader.onload = () => {
      // 转换后的base64URL reader.result
      setImg(reader.result);
    };
  };
  const addBanner = () => {
    addBannerInterface({ link, alt, img }).then((res) => {
      navigate("/banner");
    });
  };
  // 判断只要有一个内容为空,即提交禁用
  const submitFlag=link.length && alt.length && img.length
  return (
    <Space>
      <Space direction="vertical" style={{ width: 300 }}>
        {contextHolder}
        <Input
          placeholder="link"
          value={link}
          onChange={(e) => setLink(e.target.value)}
        />
        <Input
          placeholder="alt"
          value={alt}
          onChange={(e) => setAlt(e.target.value)}
        />
        <Input type="file" ref={fileRef} onChange={onChange} />
        <Input disabled placeholder="转换后的base64位地址" value={img} />
        <Image src={img} />
        <Button type='primary' disabled={!submitFlag} onClick={addBanner}>
          添加轮播图
        </Button>
      </Space>
    </Space>
  );
}
